import jwt from 'jsonwebtoken';
import { jwtSecret } from '../utils';

const exclude = [
  '/',
  '/user/login',
  '/wechat/sms/captcha',
  '/wechat/captcha/login',
  '/wechat/openid2token',
  '/wechat/hotel-info'
];

// eslint-disable-next-line consistent-return
export default function authenticateToken(req, res, next) {
  console.log('-------------------------------------req.url: ', req.url);
  console.log('-------------------------------------req.path: ', req.path);

  // Gather the jwt access token from the request header
  if (/^\/uploads/.test(req.url)
    || /^\/images/.test(req.url)
    || /^\/api-docs/.test(req.url)
    || /^\/swagger-ui/.test(req.url)
    || /^\/wechat/.test(req.url)
    || /^\/code/.test(req.url)
    || /^\/file\/upload/.test(req.url)
    || exclude.indexOf(req.url) >= 0) {
    next();
  }
  else {
    const authHeader = req.headers.authorization;
    // console.log(req.headers);

    const token = authHeader && authHeader.split(' ')[1];
    if (!token) return res.sendStatus(401); // if there isn't any token

    // eslint-disable-next-line consistent-return
    jwt.verify(token, jwtSecret, (err, user) => {
      if (err) return res.sendStatus(403);
      req.user = user;
      // console.log(user);
      next(); // pass the execution off to whatever request the client intended
    });
  }
}
